<?
session_start();
require_once 'functions.php';
require_once 'connect.php';
require_once 'PHPMailer/class.phpmailer.php';

$baseUrl = getBaseUrl();

$output = json_encode(array("status"=>"error", "message"=>"NO"));

$specId = mysql_real_escape_string($_POST['specId']);
$comment = mysql_real_escape_string($_POST['comment']);

if(isset($_SESSION['password']) && isset($_SESSION['email']) && isset($_SESSION['userId']) && isset($_POST['specId']) && isset($_POST['comment'])){

	$userId = mysql_real_escape_string($_SESSION['userId']);

	$abfrage = "
		INSERT INTO ffxivc_comments (
			userId
			,specId 
			,comment
			,cdate
			,udate)
		VALUES (
			\"".$userId."\"
			,\"".$specId."\"
			,\"".$comment."\"
			,\"".date('Y-m-d H:i:s')."\"
			,\"".date('Y-m-d H:i:s')."\")
		";
	$res = mysql_query($abfrage);
		
	if ($res){
		$abfrage = "UPDATE ffxivc_users SET posts = posts +1 WHERE userId = \"".$userId."\" ";
		$res = mysql_query($abfrage);
		if ($res){
			$output = json_encode(array("status"=>"success", "message"=>"INSERT"));
			
			$abfrage = "SELECT 
						user.email
						, user.notification 
						, user.userName
						FROM 
						((SELECT userId FROM ffxivc_specs WHERE specId = \"".$specId."\") specs   
						LEFT JOIN
						ffxivc_users user
						ON specs.userId = user.userId)";
			$res = mysql_query($abfrage);
			if ($res){
				$email = mysql_result($res, 0, "email");
				$userName = mysql_result($res, 0, "userName");
				$notification = mysql_result($res, 0, "notification");
				$sender = $_SESSION['userName'];
				if($notification == 'Y' && $userName != $sender){
					$mail = new PHPMailer(false);
					try {
						$mail->AddReplyTo('ffxivspecs@gmail.com', 'FFXIVSpecs');
						$mail->AddAddress($email, $userName);
						$mail->SetFrom('ffxivspecs@gmail.com', 'FFXIVSpecs');
						$mail->AddReplyTo('ffxivspecs@gmail.com', 'FFXIVSpecs');
						$mail->Subject = '[FFXIVSpecs] Notification';
						$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
						$mail->MsgHTML(file_get_contents($baseUrl."/php/send_email.php?action=COMMENT&comment=".urlencode($comment)."&sender=".urlencode($sender)));
						$mail->Send();
					} catch (phpmailerException $e) {
					  echo $e->errorMessage(); //Pretty error messages from PHPMailer
					} catch (Exception $e) {
					  echo $e->getMessage(); //Boring error messages from anything else!
					}
				}
			}
		}
	}
}

echo $output; 

?>